clear all;clc;close all;

Fd = 44.2e6/4; Td = 1/Fd;
tmax = 0.001; t = 0:Td:tmax;

N_PRN = 511; T_PRN = 0.001;
PRN = sign(randn(1, N_PRN));
ind_h = fix(mod(t/T_PRN, 1)*N_PRN) + 1;
h = PRN(ind_h);

N_MEANDR = N_PRN*2;
PRN_m = cos(pi*(1:N_MEANDR));
ind_h_m = fix(mod(t/T_PRN, 1)*N_MEANDR) + 1;
h_m = PRN_m(ind_h_m);

% Cигнал
A = 2;
f0 = 10e6;
phi = 0;

u = A * h_m .* h .* cos(2*pi*f0*t + phi);

d_tau = -2:0.1:2;
d_tau = d_tau * T_PRN/N_PRN;
r = nan(1,length(d_tau));

dw = 0;
dphi = 0;

for i = 1:length(d_tau)
    
    % Опора
    
    ind_h = fix(mod((t-d_tau(i))/T_PRN, 1)*N_PRN) + 1;
    h = PRN(ind_h);
    
    ind_h_m = fix(mod((t-d_tau(i))/T_PRN, 1)*N_MEANDR) + 1;
    h_m = PRN_m(ind_h_m);
    
    u_op = A * h_m .* h .* cos(2*pi*(f0+dw/2/pi)*t + phi + dphi);
    
    % Корреляционная сумма
    
    r(i) = sum(u .* u_op);
    
end

t_chip = T_PRN/N_PRN;
% Определение inline-функции ro(dtau)
ro = inline('(1 - abs(dtau/t_chip)) .* (abs(dtau)<(t_chip))', 'dtau', 't_chip');

L = fix(tmax/Td);

r_th = A*L/2 * ro(d_tau,t_chip) * sinc(dw*tmax/2/pi)*cos(dw*tmax/2+dphi);

plot(d_tau,r);

% plot(d_tau,r,d_tau,r_th);
% legend('Stat','Eq')